﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using WebSite.Models;

namespace WebSite.Controllers
{
    public class UserController : HWBaseController
    {
        // GET: /User/
        [HttpGet]
        public ActionResult Login(String returnUrl)
        {
            if (String.IsNullOrEmpty(returnUrl) && Request.UrlReferrer != null)
                returnUrl = Server.UrlEncode(Request.UrlReferrer.PathAndQuery);

            return View(new LoginVM() { ReturnUrl = returnUrl });
        }

        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult Logout()
        {
            Request.Cookies.Remove("UserId");
            FormsAuthentication.SignOut();

            return RedirectToAction("Login");
        }


        [HttpPost]
        public ActionResult Login(LoginVM loginInfo)
        {
            if (this.ModelState.IsValid)
            {
                Models.BusinessModels.User user = this.AuthenticationService.Login(loginInfo.Email, loginInfo.Password, loginInfo.IsPersistent);

                if (user != null)
                {
                    this.Response.RemoveOutputCacheItem(Url.Action("Index","About"));
                    this.Response.RemoveOutputCacheItem(Url.Action("Index","Collaboration"));
                    this.Response.RemoveOutputCacheItem(Url.Action("Index","Contact"));
                    this.Response.RemoveOutputCacheItem(Url.Action("Index","Feedback"));
                    this.Response.RemoveOutputCacheItem(Url.Action("Index","Home"));
                    this.Response.RemoveOutputCacheItem(Url.Action("Index","Placement"));
                    this.Response.RemoveOutputCacheItem(Url.Action("Index","Schedule"));
                    this.Response.RemoveOutputCacheItem(Url.Action("Index","Training"));
                    this.Response.RemoveOutputCacheItem(Url.Action("Category","Training"));
                    this.Response.RemoveOutputCacheItem(Url.Action("Course","Training"));

                    if (String.IsNullOrEmpty(loginInfo.ReturnUrl))
                    {
                        return RedirectToAction("Index", "Home");
                    }
                    return Redirect(loginInfo.ReturnUrl);
                }
                ModelState["Password"].Errors.Add("Пароли не совпадают");
            }
            return View(loginInfo);
        }
    }   
}
